package controllers;

import models.User;
import play.libs.F.Promise;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
import services.UserService;
import util.UserSession;
import exceptions.NoUUIDException;

public class Emayou extends Controller {
	public static final UserService userService = UserService.getInstance();

	// TODO refactor this boilerplate with the other controllers
	public static Result linkCallback(Long cid, Boolean success) {
		try {
			UserSession userSession = userService.getUserSession(session());

			// If filyou redirect returned a success message
			if (success) {
				User user = User.finder.where().eq("emaiyouId", cid)
						.findUnique();
				user.emaiyouLinked = true;
				user.save();
				userSession.setUser(user);// update user in memory
				// update user from cache
				userService.updateExistingUserSession(userSession);
				return redirect(routes.Connect.index());
			}

			return badRequest();
		} catch (NoUUIDException e) {
			e.printStackTrace();
		}
		return redirect(routes.Connect.index());
	}

	public static Result unlink(Long cid) {
		try {
			UserSession userSession = userService.getUserSession(session());
			User user = userSession.getUser();

			if (user.emaiyouId == cid) {
				user = User.finder.where().eq("emaiyouId", cid).findUnique();
				Promise<WS.Response> result = WS.url(
						collectors.email.controllers.routes.Application.unlink(
								cid).absoluteURL(request())).get();

				// If the HTTP STATUS is 200 than account is unlinked
				if (result.get(10000l).getStatus() == 200) {
					user.emaiyouLinked = false; // update link status
					user.save();
					userSession.setUser(user);// update user in memory
					// update user from cache
					userService.updateExistingUserSession(userSession);
				}
				return redirect(routes.Connect.index());
			} else {
				badRequest("Error trying to unlink EmaYOU");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return redirect(routes.Connect.index());
	}
}
